package endpoint

import (
	"fmt"
	"hash/fnv"

	"gitee.com/zatto/mcenter/common/meta"
)

func NewEndpintSet() *EndpointSet {
	return &EndpointSet{
		Items: []*Endpoint{},
	}
}

func (s *RegistryRequest) Add(item *CreateEndpointRequest) {
	s.Items = append(s.Items, item)
}

func NewRegistryRequest() *RegistryRequest {
	return &RegistryRequest{
		Items: []*CreateEndpointRequest{},
	}
}

func New(spec *CreateEndpointRequest) (*Endpoint, error) {

	// 计算endpoint id
	h := fnv.New32a()
	_, err := h.Write([]byte(spec.UnitKey()))
	if err != nil {
		return nil, err
	}

	ep := &Endpoint{
		Meta: meta.NewMeta(),
		Spec: spec,
	}

	ep.Meta.Id = fmt.Sprintf("%d", h.Sum32())
	return ep, nil
}

func (r *CreateEndpointRequest) UnitKey() string {
	return fmt.Sprintf("%s.%s.%s", r.ServiceId, r.Method, r.Path)
}
